package com.poetize.plus.exception;

import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.poetize.plus.utils.R;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 *
 * 全局异常捕获
 *
 * @author zuosy
 * @created 2024/3/28 19:13
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 全局捕获断言异常
     * @param exception
     * @return
     */
    @ExceptionHandler(IllegalArgumentException.class)
    public R<Integer> validatedIllegalArgumentException(IllegalArgumentException exception){
        return R.fail(null, exception.getMessage());
    }

    /**
     * validation校验异常信息捕获
     * @param exception
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> methodArgumentNotValidException(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        if (bindingResult.hasErrors()){
            List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            Set<String> messages = fieldErrors.stream().map(FieldError::getDefaultMessage).collect(Collectors.toSet());
            return R.fail(null, String.join(",", messages));
        }
        return R.fail(null, "入参异常");
    }

    /**
     * mybatis异常
     * @param exception
     * @return
     */
    @ExceptionHandler(MybatisPlusException.class)
    public R<Integer> mybatisPlusException(MybatisPlusException exception){
        return R.fail(null, "数据异常");
    }
}
